package com.cashmate.struts;



import com.cashmate.hibernate.dao.LoansDAO;
import com.cashmate.hibernate.pojo.Loans;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;


import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

public class Register_UpdateChecks extends ActionSupport{
  private LoansDAO loansDAO = (LoansDAO) ServletActionContext.getServletContext().getAttribute("loansDAO");  
  private String selected;
  private String loc;
  

  @Actions( {
    @Action(value = "/updatechecks", results = {
      @Result(location = "${loc}", name = "success", type = "redirect"), @Result(location = "${loc}", name = "input")
    })
  })

  @Override
  public String execute() throws Exception{
      loc = "/loancheckregister.jsp?cat=check";
      
      String[] sel = selected.split(",");
      String selecteds = "";
      for(String s : sel){
        try{
            int loanid = Integer.parseInt(s);
            Loans loan = loansDAO.get(loanid);
            if(!loan.getCheckses().isEmpty()){
                loan.setStatus("Registered");
                loan.setCheckprint(true);
                loansDAO.update(loan); 
            }else{
                selecteds = selecteds +  loan.getLoanid() + ",";
            }
        }catch (Exception e){
            return ERROR;
        }
      }    
      
      if(!selecteds.equals("")){
          selecteds = selecteds.substring(0, selecteds.length() - 1);
          loc = "/loancheckregister.jsp?cat=check&selected="+selecteds+"&error=yes";
      }
      

      return SUCCESS;
  }
    
    public void setSelected(String selected) {
        this.selected = selected;
    }    

    public String getLoc() {
        return loc;
    }

}
